//
//  SHHomeViewController.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/19.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit
import SVProgressHUD

// cell 可重用标识符
private let reuseIdentifier = "homeCellId"
class SHHomeViewController: SHVisitorViewController {
    
    // 模型数组
    lazy var homeDataViewModel: SHHomeDataViewModel = SHHomeDataViewModel()
    
    // 定义一个定时器
    private weak var timer: NSTimer?
    // 用于记录断网持续时间
    private var timeInterVal:NSTimeInterval = 1
    
    // MARK: - 懒加载控件
    // 菊花
    private lazy var indicatorView: UIActivityIndicatorView = {
        let view  = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        // 给菊花设置颜色
        view.color = K_THEME_COLOR
        
        return view
    }()
    // 系统下拉刷新
    private lazy var refreshControl: SHRefreshControl = {
        let control = SHRefreshControl()
        control.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        return control
    }()
    // 刷新的数据数量提示
    private lazy var refreshCountLabel:UILabel = {
        let label = UILabel(text: "", textColor: UIColor.whiteColor(), font: 12, textAlignment: .Center)
        label.frame = CGRectMake(0, 64-30, K_SCREEN_WIDTH, 30)
        label.backgroundColor = K_THEME_COLOR
        label.hidden = true
        return label
        }()
    
    // MARK: - 设置界面
    override func loadView() {
        super.loadView()
        
        if !isLogin {
            visitorView?.redesignVisitorView(nil, title: nil)
            
            return
        }
        navigationController!.view.insertSubview(refreshCountLabel, belowSubview: navigationController!.navigationBar)
        // 请求数据
        getHomeData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
        tableView.delegate = self
        // 注册cell
        tableView.registerClass(SHHomeCell.self, forCellReuseIdentifier: reuseIdentifier)
        // 预估行高
        tableView.estimatedRowHeight = 200
        // 分界线样式
        tableView.separatorStyle = .None
        // 设置 footerView
        tableView.tableFooterView = indicatorView
        // 添加子控件
        tableView.addSubview(refreshControl)
        
    }
    
    // MARK: - 下拉刷新监听
    func refreshAction(){
        getHomeData()
    }
}

// MARK: - dataSource
extension SHHomeViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeDataViewModel.dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SHHomeCell
        // 给cell赋值
        cell.userInfoViewModel = homeDataViewModel.dataArray[indexPath.row]

        return cell
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        // 如果当前显示的是最后一个cell的时候  且 当前菊花没有开始动画 才可以叫菊花转
        if indexPath.row == homeDataViewModel.dataArray.count - 1 &&
            !indicatorView.isAnimating() {
            // 开始动画
            indicatorView.startAnimating()
            self.getHomeData()
        }
    }
}
// MARK: - 请求微博数据
extension SHHomeViewController {
    
    func getHomeData() {
       self.timer?.invalidate()
        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "askForHomeData", userInfo: nil, repeats: true)
    }
    
    func askForHomeData() {

        homeDataViewModel.loadHomeData(indicatorView.isAnimating()) { (isSucc, count) -> () in
            // 断网每10秒提示一次
            if self.timeInterVal % 10 == 0 {
                SVProgressHUD.showWithStatus("亲!网路好像不给力哦")
            }
            if !isSucc {
                print("请求失败")
                self.timeInterVal += 1
                return
            }
            SVProgressHUD.dismiss()
            self.timeInterVal = 1
            // 停止动画
            self.timer?.invalidate()
            self.endRefreshing()
            // 无更多数据
            if count == -2 {
                self.setRefreshCountLabelAnim(count)
                return
            }
            self.tableView.reloadData()
            // 下拉刷新
            if count >= 0 {
                self.setRefreshCountLabelAnim(count)
            }
        }
    }
    // 停止各种动画
    func endRefreshing(){
        self.indicatorView.stopAnimating()
        self.refreshControl.endRefreshing()
    }
    // 设置微博提示动画
    func setRefreshCountLabelAnim(count: Int){
        // 判断如果当前在动画也就是显示 就不在进行动画
        if refreshCountLabel.hidden == false{
            return
        }
        // 显示空间
        refreshCountLabel.hidden = false
        var text = ""
        if count == 0 {
            text = "已经是最新数据啦"
        }else if count == -2 {
            text = "没有更多数据啦"
        }else {
            text = "更新了\(count)条微博"
        }
        // 赋值
        refreshCountLabel.text = text
        
        // 设置动画
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            
            self.refreshCountLabel.transform = CGAffineTransformMakeTranslation(0, 30)
            
            }) { (_) -> Void in
                UIView.animateWithDuration(0.5, delay: 1, options: [], animations: { () -> Void in
                    self.refreshCountLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        // 完成后隐藏
                        self.refreshCountLabel.hidden = true
                })
        }
    }

}






